package com.bz.xtcx.manager.service.impl;

import com.bz.xtcx.manager.comom.XtcxException;
import com.bz.xtcx.manager.entity.*;
import com.bz.xtcx.manager.mapper.*;
import com.bz.xtcx.manager.persist.conditions.MeetingCondition;
import com.bz.xtcx.manager.service.ICmsMeetingService;
import com.bz.xtcx.manager.service.IResCodeCreater;
import com.bz.xtcx.manager.utils.WzStrUtil;
import com.bz.xtcx.manager.vo.VoResponse;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.jms.Destination;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CmsMeetingService extends BaseService implements ICmsMeetingService {

    @Autowired
    private CmsMeetingMapper cmsMeetingMapper;

    @Autowired
    private IResCodeCreater resCodeCreater;

    @Autowired
    private LibResMapper libResMapper;

    @Autowired
    private LibReqMapper libReqMapper;

    @Autowired
    private LibServiceMapper libServiceMapper;

    @Autowired
    private LibExpertMapper libExpertMapper;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    @Autowired
    private Destination reqMeetingEmailQueue;

    @Autowired
    private Destination reqMeetingMobileQueue;

    @Autowired
    private Destination respMeetingEmailQueue;

    @Autowired
    private Destination respMeetingMobileQueue;

    @Override
    public PageInfo<CmsMeeting> getPageByCondition(MeetingCondition query, int pageNum, int pageSize) throws XtcxException {
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            throw new XtcxException("您尚未登录或已登录超时，请重新登录");
        }
        if (null != query) {
            if (null != query.getIsFormOrToMe()) {
                if (1 == query.getIsFormOrToMe()) {
                    query.setFromer(loginedUser.getUserId());
                } else if (2 == query.getIsFormOrToMe()) {
                    query.setTargeter(loginedUser.getUserId());
                    query.setTargeterCN(loginedUser.getCode());
                }
            }
        }
        Page<CmsMeeting> page = PageHelper.startPage(pageNum, pageSize);
        cmsMeetingMapper.selectByCondition(query);
        PageInfo<CmsMeeting> info = new PageInfo<CmsMeeting>(page);
        if (null != info.getList() && 0 < info.getList().size()) {
            List<CmsMeeting> listNeedRemove = new ArrayList<>();
            for (CmsMeeting cmVo : info .getList()) {
                String[] appInfo = getAppNameAndAppCodeByTypeAndId(cmVo.getTypeId(), cmVo.getApplicationContentId());
                if (appInfo != null) {
                    cmVo.setApplicationContentName(appInfo[0]);
                    cmVo.setApplicationContentCode(appInfo[1]);
                } else {
                    listNeedRemove.add(cmVo);
                }
            }
            if (!CollectionUtils.isEmpty(listNeedRemove)) {
                List<CmsMeeting> list = info.getList();
                list.removeAll(listNeedRemove);
            }
        }
        return info;
    }

    @Override
    public PageInfo<CmsMeeting> getPageForUser(MeetingCondition query, int pageNum, int pageSize) throws XtcxException {
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            throw new XtcxException("您尚未登录或已登录超时，请重新登录");
        }
        if (0 == loginedUser.getUserType() || 101 == loginedUser.getUserType()) {
            Page<CmsMeeting> page = PageHelper.startPage(pageNum, pageSize);
            cmsMeetingMapper.selectByCondition(query);
            PageInfo<CmsMeeting> info = new PageInfo<CmsMeeting>(page);
            if (null != info.getList() && 0 < info.getList().size()) {
                List<CmsMeeting> listNeedRemove = new ArrayList<>();
                for (CmsMeeting cmVo : info .getList()) {
                    String[] appInfo = getAppNameAndAppCodeByTypeAndId(cmVo.getTypeId(), cmVo.getApplicationContentId());
                    if (appInfo != null) {
                        cmVo.setApplicationContentName(appInfo[0]);
                        cmVo.setApplicationContentCode(appInfo[1]);
                    } else {
                        listNeedRemove.add(cmVo);
                    }
                }
                if (!CollectionUtils.isEmpty(listNeedRemove)) {
                    List<CmsMeeting> list = info.getList();
                    list.removeAll(listNeedRemove);
                }
            }
            return info;
        } else if (102 == loginedUser.getUserType() || 103 == loginedUser.getUserType()) {
            throw new XtcxException("您无权使用该功能");
        } else {
            if (WzStrUtil.isBlank(loginedUser.getCode())) {
                throw new XtcxException("登录用户证件信息错误");
            }
            query.setTargeterCN(loginedUser.getCode());
            if (1 == query.getIsFormOrToMe()) {
                query.setFromer(loginedUser.getUserId());
            }
            Page<CmsMeeting> page = PageHelper.startPage(pageNum, pageSize);
            cmsMeetingMapper.selectForUser(query);
            PageInfo<CmsMeeting> info = new PageInfo<CmsMeeting>(page);
            if (null != info.getList() && 0 < info.getList().size()) {
                List<CmsMeeting> listNeedRemove = new ArrayList<>();
                for (CmsMeeting cmVo : info .getList()) {
                    String[] appInfo = getAppNameAndAppCodeByTypeAndId(cmVo.getTypeId(), cmVo.getApplicationContentId());
                    if (appInfo != null) {
                        cmVo.setApplicationContentName(appInfo[0]);
                        cmVo.setApplicationContentCode(appInfo[1]);
                    } else {
                        listNeedRemove.add(cmVo);
                    }
                }
                if (!CollectionUtils.isEmpty(listNeedRemove)) {
                    List<CmsMeeting> list = info.getList();
                    list.removeAll(listNeedRemove);
                }
            }
            return info;
        }
    }

    @Override
    public CmsMeeting findById(String id) throws XtcxException {
        CmsMeeting e = cmsMeetingMapper.selectByPrimaryKey(id);
        String[] appInfo = getAppNameAndAppCodeByTypeAndId(e.getTypeId(), e.getApplicationContentId());
        if (appInfo != null) {
            e.setApplicationContentName(appInfo[0]);
            e.setApplicationContentCode(appInfo[1]);
        }
        return e;
    }

    @Override
    public CmsMeeting getById(String id) throws XtcxException {
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            throw new XtcxException("您尚未登录或已登录超时，请重新登录");
        }
        CmsMeeting e = cmsMeetingMapper.selectByPrimaryKey(id);
        String[] appInfo = getAppNameAndAppCodeByTypeAndId(e.getTypeId(), e.getApplicationContentId());
        if (appInfo != null) {
            e.setApplicationContentName(appInfo[0]);
            e.setApplicationContentCode(appInfo[1]);
        }
        return e;
    }

    @Override
    public VoResponse add(CmsMeeting t) throws XtcxException {
        VoResponse resp = new VoResponse();
        User loginedUser = getUser();
        if (null == loginedUser || WzStrUtil.isBlank(loginedUser.getUserId())) {
            resp.setFail(resp);
            resp.setMessage("您尚未登录或已登录超时，请重新登录");
            return resp;
        }
        if (0 == loginedUser.getUserType() || 101 == loginedUser.getUserType() || 102 == loginedUser.getUserType() || 103 == loginedUser.getUserType()) {
            resp.setFail(resp);
            resp.setMessage("管理员不允许发起对接");
            return resp;
        }
        // 查询即存对接信息
        MeetingCondition findCond = new MeetingCondition();
        if (WzStrUtil.isNotBlank(t.getId())) {
            findCond.setId(t.getId());
        } else {
            findCond.setFromer(loginedUser.getUserId());
            if (WzStrUtil.isNotBlank(t.getTargeter())) {
                findCond.setTargeter(t.getTargeter());
            }
            findCond.setTypeId(t.getTypeId());
            findCond.setApplicationContentId(t.getApplicationContentId());
        }
        List<CmsMeeting> meetingList = cmsMeetingMapper.selectByCondition(findCond);
        // 新增或更新对接信息
        CmsMeeting updVo = new CmsMeeting();
        String djCd = null;
        if (null == meetingList || 0 == meetingList.size()) {
            djCd = resCodeCreater.makeResCode("DJ");
            updVo.setCode(djCd);
            updVo.setTypeId(t.getTypeId());
            updVo.setFromer(loginedUser.getUserId());
            updVo.setFromerContactsName(t.getFromerContactsName());
            updVo.setFromerContactsPhone(t.getFromerContactsPhone());
            updVo.setFromerContactsMail(t.getFromerContactsMail());
            updVo.setFromerContactsAddr(t.getFromerContactsAddr());
            if (WzStrUtil.isNotBlank(t.getTargeter())) {
                updVo.setTargeter(t.getTargeter());
            } else {
                BusUser targetUserInfo = null;
                if (0 == t.getTypeId()) {
                    targetUserInfo = cmsMeetingMapper.selectExpertByResId(t.getApplicationContentId());
                } else if (1 == t.getTypeId()) {
                    targetUserInfo = cmsMeetingMapper.selectReqByResId(t.getApplicationContentId());
                } else if (2 == t.getTypeId()) {
                    targetUserInfo = cmsMeetingMapper.selectResultByResId(t.getApplicationContentId());
                } else if (3 == t.getTypeId()) {
                    targetUserInfo = cmsMeetingMapper.selectServiceByResId(t.getApplicationContentId());
                }
                if (null != targetUserInfo) {
                    updVo.setTargeter(targetUserInfo.getId());
                }
            }
            updVo.setApplicationContentId(t.getApplicationContentId());
            updVo.setApplicationNote(t.getApplicationNote());
            updVo.setSubmitTime(new Date());
            updVo.setCheckStatus(-1);
            updVo.setReqMailStatus(0);
            updVo.setReqMailCnt(0);
            updVo.setReqMobileStatus(0);
            updVo.setReqMobileCnt(0);
            updVo.setRespMobileStatus(0);
            updVo.setRespMobileCnt(0);
            updVo.setRespMailStatus(0);
            updVo.setRespMailCnt(0);
            updVo.setRefuseCount(0);
            updVo.setCreater(loginedUser.getUserName());
            updVo.setUpdater(loginedUser.getUserName());
            cmsMeetingMapper.insertSelective(updVo);
        } else if (1 == meetingList.size()) {
            if (2 <= meetingList.get(0).getRefuseCount()) {
                resp.setFail(resp);
                resp.setMessage("您已多次联系对方并被对方拒绝，请勿再次打扰");
                return resp;
            } else if (0 == meetingList.get(0).getCheckStatus()) {
                resp.setFail(resp);
                resp.setMessage("已成功通知对方，请耐心等待对方回复。若3天后仍未收到回复，请登录确认");
                return resp;
            } else if (1 == meetingList.get(0).getCheckStatus()) {
                resp.setFail(resp);
                resp.setMessage("对方已同意您的请求，可于详情查看并通过对方联系方式进行沟通");
                return resp;
            } else {
                djCd = meetingList.get(0).getCode();
                updVo.setId(meetingList.get(0).getId());
                updVo.setFromerContactsName(t.getFromerContactsName());
                updVo.setFromerContactsPhone(t.getFromerContactsPhone());
                updVo.setFromerContactsMail(t.getFromerContactsMail());
                updVo.setFromerContactsAddr(t.getFromerContactsAddr());
                updVo.setApplicationNote(t.getApplicationNote());
                if (WzStrUtil.isNotBlank(t.getTargeter())) {
                    updVo.setTargeter(t.getTargeter());
                } else {
                    BusUser targetUserInfo = null;
                    if (0 == t.getTypeId()) {
                        targetUserInfo = cmsMeetingMapper.selectExpertByResId(t.getApplicationContentId());
                    } else if (1 == t.getTypeId()) {
                        targetUserInfo = cmsMeetingMapper.selectReqByResId(t.getApplicationContentId());
                    } else if (2 == t.getTypeId()) {
                        targetUserInfo = cmsMeetingMapper.selectResultByResId(t.getApplicationContentId());
                    } else if (3 == t.getTypeId()) {
                        targetUserInfo = cmsMeetingMapper.selectServiceByResId(t.getApplicationContentId());
                    }
                    if (null != targetUserInfo) {
                        updVo.setTargeter(targetUserInfo.getId());
                    }
                }
                updVo.setCheckStatus(-1);
                updVo.setReqMailStatus(0);
                updVo.setReqMailCnt(0);
                updVo.setReqMobileStatus(0);
                updVo.setReqMobileCnt(0);
                updVo.setRespMobileStatus(0);
                updVo.setRespMobileCnt(0);
                updVo.setRespMailStatus(0);
                updVo.setRespMailCnt(0);
                updVo.setRefuseCount(0);
                updVo.setSubmitTime(new Date());
                updVo.setUpdater(loginedUser.getUserName());
                cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
            }
        } else {
            resp.setFail(resp);
            resp.setMessage("对接信息错误，请联系管理员");
            return resp;
        }
        CmsMeeting sendVo = cmsMeetingMapper.selectByCode(djCd);
        jmsMessagingTemplate.convertAndSend(reqMeetingMobileQueue, sendVo);
        jmsMessagingTemplate.convertAndSend(reqMeetingEmailQueue, sendVo);
        resp.setSuccess(resp);
        resp.setMessage("您已成功提交对接申请，请耐心等待对方回复。若3天后仍未收到回复，请登录确认");
        return resp;
    }

    @Override
    public VoResponse refuse(String id, String why) {
        VoResponse voRes = new VoResponse();
        CmsMeeting oldVo = cmsMeetingMapper.selectByPrimaryKey(id);
        if (null == oldVo) {
            voRes.setFail(voRes);
            voRes.setMessage("无对接信息或对接信息异常，请重试");
            return voRes;
        }
        User u = getUser();
//        if (null == u) {
//            voRes.setFail(voRes);
//            voRes.setMessage("您尚未登录或已登录超时，请重新登录");
//            return voRes;
//        }
        CmsMeeting updVo = new CmsMeeting();
        updVo.setId(id);
        updVo.setCheckStatus(2);
        updVo.setCheckTime(new Date());
        updVo.setCheckContent(why);
        updVo.setRefuseCount(((null == oldVo.getRefuseCount()) ? 1 : (oldVo.getRefuseCount() + 1)));
        if (null != u) {
            updVo.setUpdater(u.getUserName());
        }
        int cnt = cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
        if (1 != cnt) {
            voRes.setFail(voRes);
            voRes.setMessage("拒绝对接操作失败，请重试");
            return voRes;
        }
        CmsMeeting sendVo = cmsMeetingMapper.selectByPrimaryKey(id);
        jmsMessagingTemplate.convertAndSend(respMeetingEmailQueue, sendVo);
        jmsMessagingTemplate.convertAndSend(respMeetingMobileQueue, sendVo);
        return voRes;
    }

    @Override
    public VoResponse agree(String id) {
        VoResponse voRes = new VoResponse();
        User u = getUser();
//        if (null == u) {
//            voRes.setFail(voRes);
//            voRes.setMessage("您尚未登录或已登录超时，请重新登录");
//            return voRes;
//        }
        CmsMeeting updVo = new CmsMeeting();
        updVo.setId(id);
        updVo.setCheckStatus(1);
        updVo.setCheckTime(new Date());
        if (null != u) {
            updVo.setUpdater(u.getUserName());
        }
        int cnt = cmsMeetingMapper.updateByPrimaryKeySelective(updVo);
        if (1 != cnt) {
            voRes.setFail(voRes);
            voRes.setMessage("同意对接操作失败，请重试");
            return voRes;
        }
        CmsMeeting sendVo = cmsMeetingMapper.selectByPrimaryKey(id);
        jmsMessagingTemplate.convertAndSend(respMeetingEmailQueue, sendVo);
        jmsMessagingTemplate.convertAndSend(respMeetingMobileQueue, sendVo);
        return voRes;
    }

    @Override
    public String[] getAppNameAndAppCodeByTypeAndId(Integer typeId, String id) throws XtcxException {
        String[] rt = new String[2];
        if (0 == typeId) {
            LibExpert le = libExpertMapper.findById(id);
            if (null == le) {
                return null;
//                throw new XtcxExcption("专家信息无效");
            }
            rt[0] = le.getName();
            rt[1] = le.getNumber();
        } else if (1 == typeId) {
            LibRequirements lreq = libReqMapper.findById(id);
            if (null == lreq) {
                return null;
//                throw new XtcxException("需求信息无效");
            }
            rt[0] = lreq.getReqName();
            rt[1] = lreq.getNumber();
        } else if (2 == typeId) {
            LibResults lres = libResMapper.findById(id);
            if (null == lres) {
                return null;
//                throw new XtcxException("成果信息无效");
            }
            rt[0] = lres.getResName();
            rt[1] = lres.getNumber();
        } else if (3 == typeId) {
            LibServices ls = libServiceMapper.findById(id);
            if (null == ls) {
                return null;
//                throw new XtcxException("服务信息无效");
            }
            rt[0] = ls.getName();
            rt[1] = ls.getNumber();
        }
        return rt;
    }

    @Override
    public CmsMeeting getByCd(String cd) throws XtcxException {
        CmsMeeting e = cmsMeetingMapper.selectByCode(cd);
        if (null != e) {
            String[] appInfo = getAppNameAndAppCodeByTypeAndId(e.getTypeId(), e.getApplicationContentId());
            if (appInfo != null) {
                e.setApplicationContentName(appInfo[0]);
                e.setApplicationContentCode(appInfo[1]);
            }
        }
        return e;
    }
}
